<!--
- Author:  LiShibin.
- Date:    2017/7/4 0004.
- File:    my.
-->
<template>
  <div>
    <div class="Web_Box">
      <div class="Topmenu">
        <i @click="$utils.back" class="iconfont icon-youjiantou"><a href=""></a></i>
        <h1>确认订单</h1>
        <span></span>
      </div>
      <!--<div class="con_tab">-->
        <!--<ul class="f-cb">-->
          <!--<li class="bor-r-ddd" :class="{'cur': type == 0}" @click="switchType(0)">邮寄</li>-->
          <!--<li :class="{'cur': type == 1}" @click="switchType(1)">自提</li>-->
        <!--</ul>-->
      <!--</div>-->
      <div class="zfym">
        <div class="zfym1">
          <div v-show="addressList.requested && addressList.data.length > 0" @click="selectAddress" class="zfym_left">
            <p class="dazi"> 收货人：{{address.true_name}} <span>{{address.mob_phone}}</span> </p>
            <p>{{address.area_info}} {{address.address}}<i class="iconfont icon-youjiantou-copy" style="line-height:0px;"></i></p>
          </div>
          <div v-for="(item, index) in buyInfo.alldata" class="zfym_sp">
            <span class="zfym_sp_img">
              <!--<img :src="$config.website + $config.goodsImgSrc + item.goods_image" alt="">-->
              <img :src="$config.website + '/test.php?sign=' + index + '&image=' + item.goods_image" alt="">
            </span>
            <p>{{item.goods_name}}</p>
            <p style="color:#e3c143;">￥{{item.goods_price | discount(item.groupbuy_rebate)}}<span style="color:#333">x{{item.goods_num}}</span></p>
          </div>
          <div class="zfym_logistics">
            <span  style="margin-top: 8px;float: left;margin-left: 0px">配送方式</span> <span class="fr" style="margin-top: 8px;margin-right: 6px">平台免邮</span>
          </div>
        </div>

        <div class="fapiao">
          <p class="borbot"><span>发票 </span> <span class="fr">本次不开具发票<i class="iconfont icon-more"></i></span></p>
          <p>余额支付 <span class="yue">可用余额：{{memberInfo.balance}}</span> <input type="number" placeholder="0" v-model="balance" style="margin-top: 10px;" class="myInput"></p>
        </div>

        <div>
          <p class="heji">合计：<span style="color:#e3c143;float: none;">￥{{buyInfo.total - balance | toFixed(2)}}</span></p>
        </div>
        <div class="zfbtn">
          <span @click="selectPreferent" class="zfbtn_span">提交订单</span>
        </div>
      </div>
      <div class="ConfirmationOrder">
        <div class="OtherInfo">
          <ul>
            <!--<li style="line-height: 25px; padding-top: 10px;">-->
            <!--<p class="totalb_tis f-cb">优惠券<span class="fr Clip" @click="switchCouponShow(true)"><span class="cr_fd6847 ml10" v-if="selectedCoupon">-￥{{realCouponedMoney}}</span><span v-show="!selectedCoupon && canUseCouponNum <= 0" class=" cr_898989">无可用优惠券</span><span v-show="!selectedCoupon && canUseCouponNum > 0">使用</span><i class="iconfont icon-rightdot" style="padding-right: 10px; font-size: 12px; line-height: 24px;"></i></span>-->
            <!--</p>-->
            <!--</li>-->
            <!--<li>-->
            <!--<div class="tit">可使用余额支付</div>-->
            <!--<div class=" pr50">-->
            <!--<span class="cr_fd6847 ml10">￥{{balanceUsed | toFixed(2)}}</span>-->
            <!--&lt;!&ndash;<span class="ml10">(总余额:￥{{buyInfo.balance}})</span>&ndash;&gt;-->
            <!--</div>-->
            <!--<i v-show="!useBalance" class="iconfont icon-pitch2" style="font-size: 24px; width: 3rem; right: 0; text-align: right; margin-right: 0.5rem" @click="switchUseBalance(true)"></i>-->
            <!--<i v-show="useBalance" class="iconfont icon-select" style="font-size: 24px; width: 3rem; right: 0; text-align: right;margin-right: 0.5rem;"  @click="switchUseBalance(false)"></i></li>-->
            <!--<li style="height:55px; line-height:40px;" v-show="!selectedCoupon">-->
            <!--<div class="tit">可使用积分抵扣</div>-->
            <!--<div class=" pr50">-->
            <!--<span class="cr_fd6847 ml10">￥{{integralUsed | toFixed(2)}}</span>-->
            <!--&lt;!&ndash;<span class="ml10">(总积分:{{buyInfo.integral}})</span>&ndash;&gt;-->
            <!--<p class=" f12 cr_898989 tis ">每次购买最多可使用订单商品总额50%的积分抵扣</p>-->
            <!--</div>-->
            <!--<i v-show="!useIntegral" class="iconfont icon-pitch2" @click="switchIntegral(true)"></i>-->
            <!--<i v-show="useIntegral" class="iconfont icon-select" @click="switchIntegral(false)"></i>-->
            <!--</li>-->
            <!--<li>-->
              <!--<div class="tit">配送方式</div>-->
              <!--<div class="fr pr20 f24 cr_000">包邮</div>-->
            <!--<li class="Total" style=" height:80px;"><textarea placeholder="买家留言" v-model="remark"></textarea></li>-->
          </ul>
        </div>
      </div>
    </div>
    <!--<div class="BottomGd">-->
      <!--<span class="totals">需支付:<span class="cr_fd6847">￥{{payed | toFixed(2)}}</span></span>-->
      <!--<button class="but_3 fr bg_45a73a" type="button" @click="selectPreferent">提交订单</button>-->
    <!--</div>-->
    <!--使用优惠券弹窗-->
    <div v-show="couponModelShow">
      <div class="coupbg" style="display: block;" @click="switchCouponShow(false)">
      </div>
      <div class="coupon_box" style="max-height: 20rem; overflow-y: scroll; z-index: 9999; padding-bottom: 60px;">
        <h3>优惠方案</h3>
        <div class="ConfirmationOrder" style="margin: 0 0.5rem">
          <div class="OtherInfo">
            <ul>
              <li>
                <div class="tit">使用余额支付</div>
                <div class=" pr50">
                  <span class="cr_fd6847 ml10">￥{{balanceUsed | toFixed(2)}}</span>
                  <!--<span class="ml10">(总余额:￥{{buyInfo.balance}})</span>-->
                </div>
                <i v-show="!useBalance" class="iconfont icon-pitch2" style="font-size: 24px; width: 3rem; right: 0; text-align: center; margin-right: 0" @click="switchUseBalance(true)"></i>
                <i v-show="useBalance" class="iconfont icon-select" style="font-size: 24px; width: 3rem; right: 0; text-align: center;margin-right: 0;" @click="switchUseBalance(false)"></i>
              </li>
              <li style="height:55px; line-height:40px;">
                <div class="tit">使用积分抵扣</div>
                <div class=" pr50">
                  <span class="cr_fd6847 ml10">-￥{{integralUsed | toFixed(2)}}</span>
                  <!--<span class="ml10">(总积分:{{buyInfo.integral}})</span>-->
                  <p class=" f12 cr_898989 tis ">每次最多可用订单总额50%的积分抵扣</p>
                </div>
                <i v-show="!useIntegral" class="iconfont icon-pitch2" style="width: 3rem; right: 0; font-size: 24px;" @click="switchIntegral(true)"></i>
                <i v-show="useIntegral" class="iconfont icon-select" style="width: 3rem; right: 0; font-size: 24px;" @click="switchIntegral(false)"></i>
              </li>
            </ul>
          </div>
        </div>
        <div class="couponlist3 f-cb" style="height:auto; padding: 0 0 0 .5rem" v-for="coupon in couponList.data" v-show="coupon.is_valid == '1'">
          <div class="fl" style="position: relative; width: 11rem; height: 90px; padding-top: 0">
            <p class="c_class">{{coupon.coupon_info.coupon_abstract}}</p>
            <p class="c_money" style="padding: 0">面额：{{coupon.coupon_info.coupon_amount}}<span style="font-size: 12px;" v-show="coupon.coupon_info.coupon_type == '1'">(满{{coupon.coupon_info.coupon_need_amount}}元可用)</span>
            <p class="c_money" style="color: #000; font-size: 14px; padding: 0;">使用该优惠券抵扣：<span class="cr_fd6847">-￥{{parseFloat(coupon.total_amount) > parseFloat(coupon.coupon_info.coupon_amount) ? coupon.coupon_info.coupon_amount : coupon.total_amount}}</span>
            </p>
            <div style="position: absolute; bottom: 0; width: 100%; height: 25px; font-size: 12px; border-top: 1px dashed #aaa; line-height: 25px;" @click="toggleRangeShow(coupon)">详细信息<i v-show="coupon.rangeShow" class="iconfont icon-up" style="float: right"></i><i v-show="!coupon.rangeShow" class="iconfont icon-down-copy" style="float: right"></i>
            </div>
          </div>
          <div class="fr" style="background: none; width: 3rem" @click="selectCoupon(coupon)">
            <!--<div class="c_receive" style="width: 3rem" >-->
            <i class="iconfont icon-pitch2" style="width: 3rem; text-align: center; line-height: 4rem" v-show="!selectedCoupon || selectedCoupon.coupon_info.cm_id != coupon.coupon_info.cm_id"></i>
            <i class="iconfont icon-select" style="width: 3rem; text-align: center; line-height: 4rem; color: #45a73a; font-size: 24px;" v-show="selectedCoupon && selectedCoupon.coupon_info.cm_id == coupon.coupon_info.cm_id"></i>
            <!--</div>-->
          </div>
          <div class="fr" v-if="coupon.is_valid == '0'" style="background: #aaa; color: #fff">
            <div v-if="coupon.is_valid == '0'">不可用</div>
          </div>
          <div style="padding: 5px 0; margin-top: 90px;" v-show="coupon.rangeShow">
            <!--<p class="c_money">面额：{{coupon.coupon_info.coupon_amount}}<span style="font-size: 12px;" v-show="coupon.coupon_info.coupon_type == '1'">(满{{coupon.coupon_info.coupon_need_amount}}元可用)</span>-->
            <!--</p>-->
            <p class="c_time" style="padding-top: 0; font-size: 12px; " v-show="coupon.coupon_info.start_time != '0' && coupon.coupon_info.end_time != '0'">有效期：{{coupon.coupon_info.start_time | timestampToDate('yyyy-MM-dd')}} - {{coupon.coupon_info.end_time | timestampToDate('yyyy-MM-dd')}}</p>
            使用范围：
            <span v-for="item in coupon.coupon_info.goods_list" @click="gotoUseCoupon(item)" style=" display: inline-block; margin: 2px 2px 2px 0; padding: 2px 5px 2px 0; border-radius: 5px; font-size: 12px;">{{item.target_name}}</span>
          </div>
        </div>
        <div v-show="couponList.requested && canUseCouponNum <= 0" style="margin: 0 auto; margin-top: 5rem; text-align: center">
          当前无可用优惠券~
        </div>
        <div class="BottomGd">
          <span class="totals">需支付:<span class="cr_fd6847">￥{{payed | toFixed(2)}}</span></span>
          <button class="but_3 fr bg_45a73a" type="button" @click="submitOrder">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import {mapModules, mapRules} from 'vuet'
  import payPop from '../../components/payPop'

  export default {
    mixins: [
      mapModules({addressList: 'addressList', shopAddressList: 'shopAddressList', memberInfo: 'memberInfo'}),
      mapRules({once: ['addressList', 'shopAddressList', 'memberInfo']})
    ],
    data() {
      return {
        type: this.$route.query.type || 0, // 0 邮寄 1 自提
        deviceType: this.$utils.getDeviceType(),
        couponModelShow: false,
        selectedCoupon: null, //  选择使用的优惠券
        from: '',
        buyInfo: {total: 0, integral: 0, balance: 0, alldata: []},
        useIntegral: false,
        useBalance: false,
        remark: '', // 备注
        order: {order_id: '', pay_sn: ''}, // 提交成功后，对其赋值
        selectedCartIdList: [], // 要购买的商品的cartId列表
        couponList: {requested: false, data: []},
        realCouponedMoney: 0, // 实际优惠掉的金额
        submitIng: false, // 订单提交中
        balance: 0
      }
    },
    computed: {
      canUseCouponNum() {
        let num = 0
        for (let i = 0; i < this.couponList.data.length; i++) {
          if (this.couponList.data[i].is_valid == '1') {
            num++
          }
        }
        return num
      },
      // 抵扣的余额
      balanceUsed() {
        let balanceMony = parseFloat(parseFloat(this.buyInfo.balance).toFixed(2))
        let totalMony = parseFloat(parseFloat(this.buyInfo.total).toFixed(2))
        let remain = totalMony
        if (this.selectedCoupon) {
          console.log('ccc', totalMony, this.realCouponedMoney)
          remain = parseFloat((totalMony - this.realCouponedMoney).toFixed(2))
        }
        if (this.useIntegral) {
          remain = parseFloat((totalMony - this.integralUsed).toFixed(2))
        }
        if (remain < 0) {
          remain = 0
        }
        return balanceMony > remain ? remain : balanceMony
      },
      // 抵扣的积分金额
      integralUsed() {
        let integralMoney = parseInt(this.buyInfo.integral) // 1积分1元
        let halfTotalMoney = parseInt((parseFloat(this.buyInfo.total) / 2).toFixed(2)) // 最多可使用订单总额的50%
        return integralMoney > halfTotalMoney ? halfTotalMoney : integralMoney
      },
      // 抵扣后需支付的金额
      payed() {
        let remain = parseFloat(this.buyInfo.total)
        if (this.useIntegral) {
          remain = remain - this.integralUsed
        }
        if (this.useBalance) {
          remain = remain - this.balanceUsed
        }
        if (this.selectedCoupon) { // 使用了优惠券
          remain = remain - this.realCouponedMoney
        }
        if (remain < 0) {
          remain = 0
        }
        return remain
      },
      address() {
        if (this.$route.query.addressId) {
          for (let i = 0; i < this.addressList.data.length; i++) {
            if (this.addressList.data[i].address_id == this.$route.query.addressId) {
              return this.addressList.data[i] // 使用指定地址
            }
          }
        } else {
          for (let i = 0; i < this.addressList.data.length; i++) {
            if (this.addressList.data[i].is_default === '1') {
              return this.addressList.data[i] // 使用默认地址
            }
          }
          if (this.addressList.data.length > 0) {
            return this.addressList.data[0] // 没有默认地址，使用第一个地址
          }
        }
        return {} // 没有地址
      },
      shopAddress() {
        if (this.$route.query.shopAddressId) {
          for (let i = 0; i < this.shopAddressList.data.length; i++) {
            if (this.shopAddressList.data[i].address_id == this.$route.query.shopAddressId) {
              return this.shopAddressList.data[i] // 使用指定地址
            }
          }
        } else {
          for (let i = 0; i < this.shopAddressList.data.length; i++) {
            if (this.shopAddressList.data[i].is_default === '1') {
              return this.shopAddressList.data[i] // 使用默认地址
            }
          }
          if (this.shopAddressList.data.length > 0) {
            return this.shopAddressList.data[0] // 没有默认地址，使用第一个地址
          }
        }
        return {} // 没有地址
      }
    },
    components: {},
    created() {
      console.log('query', this.$route.query.cart)
      this.selectedCartIdList = this.$route.query.cart.toString().split(',')
      console.log('cartIdList', this.$route.query, this.selectedCartIdList)
      this.getBuyInfo(this.selectedCartIdList)
      this.getCanUseCouponList()
    },
    watch: {
      $route() {
        this.type = this.$route.query.type
      },
      balance: function () {
        if (parseFloat(this.balance) > parseFloat(this.memberInfo.balance)) {
          this.balance = this.memberInfo.balance
          this.$toast('输入的余额不能超过拥有的')
        }
        if (this.balance > parseFloat(this.buyInfo.total)) {
          this.$toast(this.balance.toString())
          this.balance = this.buyInfo.total
        }
        if (this.balance > 0) {
          this.useBalance = true
        }
      }
    },
    methods: {
      gotoUseCoupon(item) {
        if (item.type == 'all_gc') {
          this.$router.push({name: 'goods-classify'})
        } else if (item.type == 'all_stc') {
          this.$router.push({name: 'goods-classify', query: {id: item.target_id}})
        } else if (item.type == 'goods') {
          this.$router.push({name: 'goods-detail', params: {id: item.target_id}})
        }
      },
      toggleRangeShow(coupon) {
        coupon.rangeShow = !coupon.rangeShow
      },
      switchCouponShow(boolValue) {
        this.couponModelShow = boolValue
        if (boolValue) {
          this.$utils.addBodyFix() // 显示模态框，防止滚动模态框里的div时body也滚动
        } else {
          this.$utils.removeBodyFix()
        }
      },
      selectCoupon(coupon) {
        if (this.selectedCoupon == coupon) {
          this.selectedCoupon = null
          this.realCouponedMoney = 0
        } else {
          this.selectedCoupon = coupon
          this.useIntegral = false
          this.realCouponedMoney = parseFloat(coupon.total_amount) > parseFloat(coupon.coupon_info.coupon_amount) ? coupon.coupon_info.coupon_amount : coupon.total_amount
        }
        // this.switchCouponShow(false)
      },
      getCanUseCouponList() {
        let use_client
        if (this.deviceType == 'wx-Android' || this.deviceType == 'wx-iPhone') {
          use_client = '2'
        } else if (this.deviceType == 'APICloud') {
          use_client = '1'
        }
        this.$request.getCanUseCouponList(this.selectedCartIdList, use_client).then(data => {
          data.sort(function (a, b) {
            return b.coupon_info['total_amount'] - a.coupon_info['total_amount'] // 可抵扣金额降序
          })
          let canUseDataList = []
          for (let i = 0; i < data.length; i++) {
            data[i].rangeShow = false
            if (data[i].is_valid == '1') {
              canUseDataList.push(data[i])
            }
          }
          this.couponList.data = canUseDataList
          let maxCouponMoneyIndex = 0
          let counponMaxMoney = 0
          for (let i = 0; i < canUseDataList.length; i++) {
            let couponMoney = parseFloat(canUseDataList[i].coupon_info.coupon_amount)
            if (couponMoney > counponMaxMoney) {
              counponMaxMoney = couponMoney
              maxCouponMoneyIndex = i
            }
          }
          if (counponMaxMoney == 0) {
            this.useIntegral = true
          } else {
            this.selectCoupon(canUseDataList[maxCouponMoneyIndex])
          }
          // if (canUseDataList.length > 0) {
          //   this.selectCoupon(canUseDataList[0])
          // } else {
          //   this.useIntegral = true
          // }
        }).finally(() => {
          this.couponList.requested = true
        })
      },
      switchSelectCoupon(coupon) {
        if (coupon.is_canUse == '0') {
          return
        }
        this.selectedCoupon = coupon
      },
      cancleUseCoupon() {
        this.selectedCoupon = null
        this.switchCouponShow(false)
      },
      switchType(value) {
        this.$router.replace({name: 'order-confirm', query: {cart: this.$route.query.cart, type: value}})
      },
      switchUseBalance(boolValue) {
        this.useBalance = boolValue
      },
      switchIntegral(boolValue) {
        if (this.integralUsed < 0 && !boolValue) { // 积分为负数时，不让用户取消勾选，必须要多付款，抹平积分。
          return
        }
        if (boolValue) {
          this.selectedCoupon = null
        }
        this.useIntegral = boolValue
      },
      gotoAddAddress() {
        this.$router.push({
          name: 'address-add',
          query: {from: 'order-confirm', cart: this.$route.query.cart, type: this.type}
        })
      },
      getBuyInfo(idList) {
        this.$request.getBuyInfo(idList).then(data => {
          this.buyInfo = data
        })
      },
      selectAddress() {
        this.$router.push({
          name: 'address-list',
          query: {from: 'order-confirm', cart: this.$route.query.cart, type: this.type}
        })
      },
      selectShopAddress() {
        this.$router.push({
          name: 'address-shop',
          query: {from: 'order-confirm', cart: this.$route.query.cart, type: this.type}
        })
      },
      selectPreferent() {
        let address_id = ''
        if (this.type == 0) { // 邮寄
          address_id = this.address.address_id
        } else if (this.type == 1) { // 自提
          address_id = this.shopAddress.address_id
        }
        if (!address_id) {
          this.$toast('请先选择地址')
          this.$router.push({name: 'address-list'})
          return
        }
        if (this.type == 0 && (this.address.area_info.indexOf('新疆') > -1 || this.address.area_info.indexOf('西藏') > -1)) {
          this.$messageBox.confirm('<p>偏远地区（新疆、西藏）运费需自理</br>详情请联系客服<a href="tel:4000770591">4000770591</a></br>如有不便，敬请谅解！</p>', '提示').then(data => {
          }).catch(e => {
          })
        } else {
          this.submitOrder()
        }
      },
      submitOrder() {
        if (this.submitIng) {
          return
        }
        let param = {
          cart_id: this.selectedCartIdList,
          ifcart: 1,
          is_balance: this.useBalance ? 1 : 0,
          is_integral: this.useIntegral ? 1 : 0,
          order_note: this.remark,
          pay_name: 'online',
          self: this.type,
          balance: this.balance
        }
        if (this.selectedCoupon) {
          param.cm_id = this.selectedCoupon.coupon_info.cm_id
        }
        if (this.type == 0) { // 邮寄
          param.address_id = this.address.address_id
        } else if (this.type == 1) { // 自提
          param.address_id = this.shopAddress.address_id
        }
        if (!param.address_id) {
          this.$toast('请先选择地址')
          return
        }
        this.submitIng = true
        this.$request.submitOrder(param).then(data => {
          this.submitIng = false
//          this.$toast('提交订单成功')
          this.switchCouponShow(false)
          this.selectedCartIdList = []
          this.order = data
          if (this.balance - this.buyInfo.total == 0) { // 通过帐号余额支付，不需要走第三方支付
            this.$router.replace({name: 'order-success', query: {id: this.order.order_id}})
            return
          }
          let paySn = this.order.pay_sn
          payPop({paySn: paySn, orderId: this.order.order_id}, this.canclePay)
        }).catch(e => {
          this.submitIng = false
          this.$toast('订单提交失败:' + e.msg)
        })
      },
      canclePay() {
        this.$router.replace({name: 'order-detail', params: {id: this.order.order_id}})
      }
    }
  }
</script>

<style>
  .coupon-selected {
    border: 1px solid #3fbc6e;
  }

  .coupon_box .icon-pitchon2 {
    display: block;
    width: 3rem;
    line-height: 34px;
    text-align: right;
    color: white !important;
    font-size: 20px;
  }

  .coupon_box .icon-pitch2 {
    display: block;
    width: 3rem;
    line-height: 34px;
    text-align: right;
    color: #aaa;
    font-size: 24px;
  }
  .myInput {
    text-align: right;
    border: none;
    background: none;
    position: absolute;
    height: 30px;
    width: 80%;
    top: 0;
    right: 0;
    float: right;
  }
</style>
